package com.x.websocket;

import java.io.IOException;
import javax.websocket.ClientEndpoint;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <p>
 * .
 *
 * @author o_o
 * @date 2024-06-09
 */
@ClientEndpoint
@Data
@Slf4j
@Component
public class WebSocketClient {

    private Session session;

    /**
     * 建立连接成功调用的方法.
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        log.info("{} 连接建立成功.", session);
    }

    /**
     * 连接关闭调用的方法.
     */
    @OnClose
    public void onClose() {
        log.info("{} 连接断开", session.getId());
    }

    /**
     * .
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自: {} 的消息：{}", session, message);
    }

    @OnError
    public void onError(Session session, Throwable exception) {
        log.error("{} error", session, exception);
    }

    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("send msg[ {} ] error. {}", message, e.getMessage(), e);
        }
    }


}
